package assist.base

import java.io.Closeable
import java.io.File
import java.io.InputStream
import java.io.OutputStream

object FixApk {
    private const val apkVersion = "401" // 版本
    @JvmStatic
    fun main(args: Array<String>) {
        val apkPath = "D:\\Projects\\immx\\app\\build\\outputs\\apk\\immx\\release\\app_s_v${apkVersion}.apk"
        val apkFile = File(apkPath)
        println("打包结果地址")
        println(apkPath)
        if (!apkFile.exists()) {
            println("没有打包出apk 版本 $apkVersion")
            return
        }
        val outputApkPath = "D:\\apks\\app_bx_v${apkVersion}.apk"
        println("复制apk文件开始 $apkVersion")
        copy(apkFile.inputStream(), File(outputApkPath).outputStream())

        val mappingPath = "D:\\Projects\\immx\\app\\build\\outputs\\mapping\\immxRelease\\mapping.txt"
        val mappingFile = File(mappingPath)
        val outputMappingPath = "D:\\apks\\mapping${apkVersion}.txt"
        println("复制mapping文件开始")
        copy(mappingFile.inputStream(), File(outputMappingPath).outputStream())
        println("复制mapping文件已完成")

        val outputApkZipPath = "D:\\apks\\app_bx_v${apkVersion}.zip"
        ZipUtils.encryptToZip(outputApkPath, outputApkZipPath,"f9bd4acc4bb56ad14ff9fc25bc5fe177")
        println("apk zip 密码压缩完成")
        // ZipUtils.decryptZip(outputApkZipPath, "E:\\apks\\app_v${apkVersion}_unzip", "f9bd4acc4bb56ad14ff9fc25bc5fe177")
    }

    private fun copy(inputStream: InputStream?, outputStream: OutputStream?) {
        if (inputStream == null) return
        if (outputStream == null) return
        try {
            var read: Int
            val bytes = ByteArray(1024)
            while (inputStream.read(bytes).also { read = it } != -1) {
                outputStream.write(bytes, 0, read)
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        } finally {
            inputStream.closeQuietly()
            outputStream.closeQuietly()
        }
    }

    private fun Closeable.closeQuietly() {
        try {
            close()
        } catch (rethrown: RuntimeException) {
            throw rethrown
        } catch (_: Exception) {
        }
    }
}